<template>
<!--从后端返回信息部分-->
<el-form :model="formInline" :rules="credit_list_rules" ref="form" :label-position=" 'right' " label-width="90px"
				 :inline="true">

	<el-form-item label="处理方">
		<FuzzySearchHandleVer2 @DataUse="handle_auto_complete_in_record($event as any)"
											 ref="handle_clear"
											 :disable="false"
		                   @DataClear="handle1_clear"/>
	</el-form-item>

	<el-form-item label="处理方分组">
		<FuzzySearchHandleClassVer2 @DataUse="handle_class_auto_complete_in_record($event as any)"
														ref="handle_class_clear"
														:disable="false"
														@DataClear="handle_class1_clear"/>
	</el-form-item>

	<el-form-item prop="use" label="启用状态">
		<el-radio-group v-model="formInline.use">
			<el-radio-button :label="true">启用</el-radio-button>
			<el-radio-button :label="false">未启用</el-radio-button>
		</el-radio-group>
	</el-form-item>

	<el-form-item>
		<el-button type="primary" @click="return_credit_list()">提交</el-button>
	</el-form-item>

</el-form>

<!--前端直接筛选信息部分-->
<el-form :label-position=" 'right' " label-width="90px" :inline="true">
	<el-form-item prop="staff" label="处理方名称">
		<el-input v-model="search1" placeholder="页面内搜索用"/>
	</el-form-item>
	<el-form-item>
		<el-button @click=" search2 = search1.trim() ">页面内搜索</el-button>
		<el-button @click=" search2 = ''; search1 = '' ">清空搜素</el-button>
		<el-button @click=" handleAdd() ">添加处理方</el-button>
	</el-form-item>
</el-form>

<!-- 表格部分 -->
<el-table :data="filterTableData" style="width: 100%">
	<!--选择框-->
	<el-table-column label="编号" prop="id" v-if=" false "/>
	<el-table-column label="分组编号" prop="handle_group_id" v-if=" false "/>
	<el-table-column label="处理方名称" prop="handle"/>
	<el-table-column label="助记码" prop="mnemonic"/>
	<el-table-column label="分组" prop="handle_group__name"/>
	<el-table-column label="供应商余额" prop="balance"/>
	<el-table-column label="修改人" prop="creator"/>
	<el-table-column label="创建时间" prop="creation_date_str"/>
	<el-table-column label="是否启用">
		<template #default="scope">
			<!--      <span>{{scope.row._use ? '是':'否'}}</span>-->
			<el-switch v-model="scope.row.use" size="small" @click="switch_change(scope.row)"/>
		</template>
	</el-table-column>

	<el-table-column align="right">
		<template #header>
		</template>

		<template #default="scope">
			<el-button size="small" @click="handleEdit(scope.row)"
			>修改
			</el-button
			>
			<el-button
				size="small"
				type="danger"
				@click="handleDelete(scope.$index, scope.row)"
			>删除
			</el-button
			>
		</template>
	</el-table-column>
</el-table>

<el-pagination
	v-model:current-page="currentPage"
	v-model:page-size="pageSize"
	:page-sizes="[100, 200, 500]"
	:small="small"
	:disabled="disabled"
	:background="background"
	layout="total, sizes, prev, pager, next, jumper"
	:total=" total "
/>

<!--添加/修改处理方-->
<el-dialog v-model="dialogFormVisible"
					 :title=" add_revise "
					 :close-on-click-modal='false'
					 :close-on-press-escape='false'
					 :show-close='false'>
	<el-form :model="crud_handle" :rules="handle_member_rules" ref="crud_form" :label-position=" 'right' " label-width="120px">
		<!-- :rules="rules" -->
		<el-form-item prop="handle_name" label="处理方名称">
			<el-input v-model="crud_handle.handle_name" autocomplete="off"/>
		</el-form-item>

		<el-form-item prop="mnemonic" label="助记码">
			<el-input v-model="crud_handle.mnemonic" autocomplete="off"/>
		</el-form-item>

		<el-form-item prop="group_name" label="处理方分组">
			<FuzzySearchHandleClassVer2 @DataUse="handle_class_auto_complete_in_handle_dialog($event as any)"
															ref="handle_class_clear"
															:disable="false"
															:content=" '' "/>
		</el-form-item>

	</el-form>
	<template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false; crud_form?.clearValidate()">取消</el-button>
        <el-button type="primary" @click="add_or_revise()">
          保存
        </el-button>
      </span>
	</template>
</el-dialog>


</template>

<script lang="ts" setup>
import {
	computed, ComputedRef,
	reactive, Ref,
	ref, watch,
} from 'vue'
import {ElMessage, ElMessageBox} from "element-plus";
import type {FormInstance, FormRules} from 'element-plus'
// import {Router, useRouter} from 'vue-router'
import {useStore} from "@/pinia"
import type {HandleAutoCompletion} from "@/components/first/FuzzySearchHandleVer2.vue";
import type {HandleClassAutoCompletion} from "@/components/first/FuzzySearchHandleClassVer2.vue";
import {HandleMemberCRUDResponse, HandleMemberList} from "@/api/first/HandleManagement/type.ts";
import {reqHandleMemberCRUD} from "@/api/first/HandleManagement";
import FuzzySearchHandleVer2 from "@/components/first/FuzzySearchHandleVer2.vue";
import FuzzySearchHandleClassVer2 from "@/components/first/FuzzySearchHandleClassVer2.vue";

const store = useStore()
// const router: Router = useRouter()


const handle1_clear = () => {
	handle_clear.value.clear_input()
	formInline.handle_id = ''
}

const handle_class1_clear = () => {
	handle_class_clear.value.clear_input()
	formInline.group_id = ''
}

// 通过开关来修改处理方的使用/未使用状态
// ===============================
const switch_change = async (row: HandleMemberList) => {
	const result: HandleMemberCRUDResponse = await reqHandleMemberCRUD({
		mode: 'update',
		update: {
			handle_name: row.handle,
			mnemonic: row.mnemonic,
			creator: store.username,
			id: row.id,
			group_id: row.handle_group_id,
			use: row.use,
		}
	}).catch(() => {
		row.use = !row.use
	})
	// 修改成功
	row.creator = store.username
	row.creation_date_str = result.update as string
	ElMessage.success(result.success?.message)
}


// 通过处理方名称前端记录过滤
// ======================
const search1: Ref<string> = ref('') // 输入框中的内容
const search2: Ref<string> = ref('') // 实际进行模糊搜索的内容

const filterTableData: ComputedRef<HandleMemberList[]> = computed(() =>
	tableData.value.filter(
		(data) => !search2.value || data.handle.includes(search2.value)
	)
)

// 按照条件从后端返回数据 助记码和处理方名称使用模糊搜索
// =============================================
const handle_clear = ref()
const handle_class_clear = ref()

const handle_auto_complete_in_record = (cmy: HandleAutoCompletion) => {
	formInline.handle_id = cmy.handle_id as number
	formInline.group_id = ''
	handle_class_clear.value.clear_input()
}

const handle_class_auto_complete_in_record = (cmy: HandleClassAutoCompletion) => {
	formInline.group_id = cmy.handle_class_id as number
	formInline.handle_id = ''
	handle_clear.value.clear_input()
}

// 向后端返回的检索条件
const formInline = reactive<{
	handle_id: '' | number,
	use: boolean,
	group_id: '' | number,
}>({
	handle_id: '',
	use: true,
	group_id: ''
})

// el-form 的ref
const form = ref<FormInstance>()

// 对后端进行校验
const credit_list_rules = reactive<FormRules>({
	staff: [{
		type: 'string',
		message: '处理方名称应小于等于十个字符',
		max: 10,
		min: 1,
	}],
	mnemonic: [{
		type: 'string',
		message: '助记码应小于等于十个字符',
		max: 10,
		min: 1
	}],
})


// 提交信息以便获取表单，提交内容包括根据分页确定起始条数
const return_credit_list = async () => {
	await form.value?.validate()
	// 若表单验证无误
	const result: HandleMemberCRUDResponse = await reqHandleMemberCRUD({
		mode: 'read',
		read: {
			id: formInline.handle_id as number,
			group_id: formInline.group_id as number,
			use: formInline.use,
			start: (currentPage.value - 1) * pageSize.value,
			stop: currentPage.value * pageSize.value,
		}
	})
	tableData.value = result.read?.handle_list as HandleMemberList[]
	total.value = result.read?.total as number
	ElMessage.success(result.success?.message)
}

// 通过增加和修改按钮对处理方的增加和修改
let dialogFormModel: string = '' // 决定这个框到底是 修改框还是添加框，只会被赋值为modify和add
const dialogFormVisible: Ref<boolean> = ref(false) // 决定 修改/添加角色框 是否显示
const add_revise: Ref<string> = ref('') // 表单的标题
const crud_form = ref<FormInstance>() // 增删改的表单的ref
// 弹出框的字段
const crud_handle = reactive<{
	handle_name: string
	mnemonic: string
	use: boolean
	handle_id: number | ''
	group_id: number | ''
	group_name: string
}>({
	handle_name: '',
	mnemonic: '',
	use: true,
	handle_id: '',
	group_id: '',
	group_name: ''
})

const handle_class_auto_complete_in_handle_dialog = (cmy: HandleClassAutoCompletion) => {
	crud_handle.group_id = cmy.handle_class_id
	crud_handle.group_name = cmy.handle_class_name
}

// 添加/删除框的校验
const handle_member_rules = reactive<FormRules>({
	handle_name: [{
		type: 'string',
		message: '处理方名称应小于等于30个字符',
		max: 30,
		min: 1,
		required: true,
	}],
	mnemonic: [{
		type: 'string',
		message: '助记码应小于等于30个字符',
		max: 30,
		min: 1,
		required: true,
	}],
	group_name: [{
		type: 'string',
		required: true,
		message: '请选择分组',
	}],
})




// 修改处理方信息
const handleEdit = (row: HandleMemberList) => {
	dialogFormVisible.value = true
	add_revise.value = '修改处理方信息'
	crud_handle.handle_name = row.handle
	crud_handle.mnemonic = row.mnemonic
	crud_handle.use = row.use
	crud_handle.handle_id = row.id
	crud_handle.group_id = row.handle_group_id
	dialogFormModel = 'modify'
	handle_class_clear.value.make_input_value(row.handle_group__name)
}

// 添加处理方
const handleAdd = () => {
	dialogFormVisible.value = true
	add_revise.value = '添加处理方信息'
	crud_handle.handle_name = ''
	crud_handle.mnemonic = ''
	crud_handle.use = true
	dialogFormModel = 'add'
}

// 提交添加和修改信息
const add_or_revise = async () => {
	await crud_form.value?.validate()

	// 添加处理方信息
	if (dialogFormModel === 'add') {
		const result: HandleMemberCRUDResponse = await reqHandleMemberCRUD({
			mode: 'create',
			create: {
				handle_name: crud_handle.handle_name.trim(),
				mnemonic: crud_handle.mnemonic.trim(),
				use: crud_handle.use,
				creator: store.username,
				group_id: crud_handle.group_id as number,
			}
		})
		dialogFormVisible.value = false
		ElMessage.success(result.success?.message)
	} else {
		// 修改处理方信息
		const result: HandleMemberCRUDResponse = await reqHandleMemberCRUD({
			mode: 'update',
			update: {
				handle_name: crud_handle.handle_name.trim(),
				mnemonic: crud_handle.mnemonic.trim(),
				use: crud_handle.use,
				id: crud_handle.handle_id as number,
				creator: store.username,
				group_id: crud_handle.group_id as number,
			}
		})
		dialogFormVisible.value = false
		ElMessage.success(result.success?.message)
	}
	crud_form.value?.clearValidate()
}

// 通过每条记录后的删除按钮进行删除
// ===========================
const handleDelete = async (index: number, row: HandleMemberList) => {
	crud_handle.handle_id = row.id
	await ElMessageBox.confirm(
		`您确认删除名称为 ${row['handle']} 的处理方？`,
		'警告',
		{
			confirmButtonText: '确认',
			cancelButtonText: '取消',
			type: 'warning',
		}
	)
	const result: HandleMemberCRUDResponse = await reqHandleMemberCRUD({
		mode: 'delete',
		delete: {
			id: crud_handle.handle_id as number,
		}
	})
	tableData.value.splice(index, 1)
	// 记得分页中的total需要减去1
	total.value = total.value - 1
	ElMessage.success(result.success?.message)
}
// 分页功能
// ======

// 返回页面数据
const return_handle_member = () => {
	// 进行检查
	if(formInline.handle_id === '' && formInline.group_id === ''){
		ElMessage.warning('请选择分组或处理方')
		return
	}
	reqHandleMemberCRUD({
		mode: 'read',
		read: {
			id: formInline.handle_id as number,
			group_id: formInline.group_id as number,
			use: formInline.use,
			start: (currentPage.value - 1) * pageSize.value,
			stop: currentPage.value * pageSize.value,
		}
	}).then((res: HandleMemberCRUDResponse) => {
		tableData.value = res.read?.handle_list as HandleMemberList[]
		total.value = res.read?.total as number
		ElMessage.success(res.success?.message)
	})
}




const tableData: Ref<HandleMemberList[]> = ref([])

const background: Ref<boolean> = ref(true)  // 是否带背景方框
const disabled: Ref<boolean> = ref(false)  // 是否可用
const small: Ref<boolean> = ref(false)  // 普通大小还是小一号
const currentPage: Ref<number> = ref(1)  // 当前所在页数
const pageSize: Ref<number> = ref(100)  // 一页有几条记录

const total: Ref<number> = ref(0) // 总条数

// 监控两个数，一个是当前所在页，一个是每页条数有无发生变化，每页条数发生变化后直接回到第一页
// 同时监视所在页数和一页有几条记录两者的变化
watch([currentPage, pageSize], () => {
	// console.log(value, pageSize4.value)
	// console.log((newCurrentPage - 1) * pageSize.value + 1, newCurrentPage * pageSize.value)
	// 页面生成后立即执行一次
	return_handle_member()
})
</script>